package com.time.store.news.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.time.store.news.consts.NewsPositionEnum;
import com.time.store.news.entity.bo.NewsInfo;
import com.time.store.news.entity.dto.NewsCategoryDTO;
import com.time.store.news.entity.dto.NewsDTO;
import com.time.store.news.mapper.NewsInfoMapper;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NewsInfoService extends ServiceImpl<NewsInfoMapper, NewsInfo> implements IService<NewsInfo> {


    public List<NewsCategoryDTO> getHomeNews() {
        // 获取新闻列表
        List<NewsCategoryDTO> newsCategoryDTOS = baseMapper.selectByPosition(NewsPositionEnum.HOME_RIGHT.getKey());
        // 新闻列表按照权重和时间排序 (因为sql里对新闻权重和时间排序 会导致多表排序,不会进行索引 所以放在代码中排序)
        newsCategoryDTOS.forEach(cateGoryItem -> {
            if (CollectionUtil.isEmpty(cateGoryItem.getNews())) {
                return;
            }
            List<NewsDTO> news = cateGoryItem.getNews();
            cateGoryItem.setNews(news
                    .stream()
                    .sorted(Comparator.comparing(NewsDTO::getCreateTime))
                    .sorted(Comparator.comparing(NewsDTO::getWeight))
                    .limit(5)
                    .collect(Collectors.toList()));
        });
        return newsCategoryDTOS;
    }

    public List<NewsDTO> getFunctionNew() {
        List<NewsDTO> newsDTOS = baseMapper.selectNewsByPosition(NewsPositionEnum.FUNCTIONALLY_NEW.getKey());
        return newsDTOS;
    }

}
